package com.chat.common.user.service.impl;

import com.chat.common.common.annotation.RedissonLock;
import com.chat.common.common.domain.vo.resp.ApiResult;
import com.chat.common.common.domain.vo.resp.IdRespVO;
import com.chat.common.common.utils.AssertUtil;
import com.chat.common.user.dao.UserEmojiDao;
import com.chat.common.user.domain.entity.UserEmoji;
import com.chat.common.user.domain.vo.req.user.UserEmojiReq;
import com.chat.common.user.domain.vo.resp.user.UserEmojiResp;
import com.chat.common.user.service.UserEmojiService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserEmojiServiceImpl implements UserEmojiService {

    @Resource
    private UserEmojiDao userEmojiDao;

    @Override
    public List<UserEmojiResp> list(Long uid) {
        return userEmojiDao.listByUid(uid).stream().map(a -> UserEmojiResp.builder()
                .id(a.getId())
                .expressionUrl(a.getExpressionUrl())
                .build()).collect(Collectors.toList());
    }

    @Override
    @RedissonLock(key = "#uid")
    public ApiResult<IdRespVO> insert(UserEmojiReq req, Long uid) {
        Integer count = userEmojiDao.countByUid(uid);
        AssertUtil.isFalse(count>30,"每个用户最多添加30个表情包");
        //检查表情包是否存在
        Integer existsCount = userEmojiDao.existsCount(req, uid);
        AssertUtil.isFalse(existsCount>0,"表情包已存在,无需重复添加");
        UserEmoji insert = UserEmoji.builder()
                .expressionUrl(req.getExpressionUrl())
                .uid(uid)
                .build();
        userEmojiDao.save(insert);
        return ApiResult.success(IdRespVO.id(insert.getId()));
    }

    @Override
    public void remove(long id, Long uid) {
        UserEmoji userEmoji = userEmojiDao.getById(id);
        AssertUtil.isNotEmpty(userEmoji, "表情不能为空");
        AssertUtil.equal(userEmoji.getUid(), uid, "小黑子，别人表情不是你能删的");
        userEmojiDao.removeById(id);
    }


}
